package com.cn.medicalcare.service.serviceimpl;

import com.cn.medicalcare.customtool.JsonTool;
import com.cn.medicalcare.customtool.SqlSessionFactoryTool;
import com.cn.medicalcare.mapper.AdminMapper;
import com.cn.medicalcare.pojo.Admin;
import com.cn.medicalcare.pojo.AllPage;
import com.cn.medicalcare.service.AdminService;
import org.apache.commons.codec.digest.DigestUtils;

import java.util.List;

public class AdminServiceImpl implements AdminService {
    private static final String PREFIX = "pOiIVciO";
    private static final String SUFFIX = "Nlvo";


    //静态内部类单例模式
    private static class SingletonClassInstance {
        private static final AdminServiceImpl instance = new AdminServiceImpl();
    }

    private AdminServiceImpl() {
    }

    public static AdminServiceImpl getInstance() {
        return SingletonClassInstance.instance;
    }

    @Override
    public Admin selectAdminByUsername(String username) {
        return SqlSessionFactoryTool.DoMapper(AdminMapper.class, m -> m.selectAdminByName(username));
    }

    @Override
    public boolean insertAdmin(Admin admin) {
        admin.setPassword(encryption(admin.getUsername()));
        return SqlSessionFactoryTool.DoMapperAndCommit(AdminMapper.class, m -> m.insertAdmin(admin));
    }

    @Override
    public boolean updataAdmin(Admin admin) {
        return SqlSessionFactoryTool.DoMapperAndCommit(AdminMapper.class, m -> m.updateAdmin(admin));
    }

    @Override
    public boolean updataAdminPassword(Admin admin) {
        admin.setPassword(encryption(admin.getPassword()));
        return SqlSessionFactoryTool.DoMapperAndCommit(AdminMapper.class, m -> m.updateAdminPassword(admin));
    }

    @Override
    public List<Admin> selectAdminInPage(AllPage<Admin> allPage) {
        List<Admin> list = SqlSessionFactoryTool.DoMapper(AdminMapper.class, m -> m.selectAdminInPage(allPage));
        return list;
    }

    @Override
    public int selectAdminCount(Admin admin) {
        return SqlSessionFactoryTool.DoMapper(AdminMapper.class, m -> m.selectAdminCount(admin));
    }

    /**
     * MD5 加密
     *
     * @param password 原始密码
     * @return 加密后的密码
     */
    public String encryption(String password) {
        return DigestUtils.md5Hex(AdminServiceImpl.PREFIX + password + AdminServiceImpl.SUFFIX);
    }

}
